/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-06-01     liuchao       the first version
 */
#define LOG_TAG "watchdog"
#include <ulog.h>
#include "board.h"
#include "sleep.h"
#include "configuration.h"

#define WDT_DEVICE_NAME    "wdt"    /* 看门狗设备名称 */

static rt_device_t wdg_dev; /* 看门狗设备句柄 */

static void idle_hook(void)
{
    /* 在空闲线程的回调函数里喂狗 */
    rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_KEEPALIVE, NULL);
    LOG_D("feed the dog!");
}
static int init_watch_dog()
{
    ulog_tag_lvl_filter_set(LOG_TAG, LOG_LVL_INFO);
    rt_uint32_t sleep_time = sleep_seconds_get();
    if (sleep_time > 0)
    {
        LOG_W("Watch dog not setup, for device will standby %lu", sleep_time);
    }
    else
    {
        rt_uint32_t timeout = 10;
        /* 根据设备名称查找看门狗设备，获取设备句柄 */
        wdg_dev = rt_device_find(WDT_DEVICE_NAME);
        if (!wdg_dev)
        {
            LOG_E("find %s failed!", WDT_DEVICE_NAME);
            return RT_ERROR;
        }
        /* 初始化设备 */
        rt_device_init(wdg_dev);
        /* 设置看门狗溢出时间 */
        int ret = rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_SET_TIMEOUT, &timeout);
        if (ret != RT_EOK)
        {
            LOG_E("set %s timeout failed!", WDT_DEVICE_NAME);
            return RT_ERROR;
        }
        /* 启动看门狗 */
        ret = rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_START, RT_NULL);
        if (ret != RT_EOK)
        {
            LOG_E("start %s failed!", WDT_DEVICE_NAME);
            return -RT_ERROR;
        }
        /* 设置空闲线程回调函数 */
        rt_thread_idle_sethook(idle_hook);

    }
    standby_seconds(sleep_time);
    return RT_EOK;
}
INIT_APP_EXPORT(init_watch_dog);
